package com.jxchexie.signin;

import android.content.Context;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import androidx.appcompat.widget.Toolbar;

import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.utils.TimeUtils;
import com.bumptech.glide.Glide;
import com.jxchexie.api.Api;
import com.jxchexie.app.App;
import com.jxchexie.model.HeadImage;
import com.jxchexie.model.MyMessage;
import com.jxchexie.model.ResponseLogin;
import com.jxchexie.utils.JsonUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.Response;

public class UserActivity extends AppCompatActivity {
    private Button QiutBtn;
    private TextView user;
    private Toolbar settingsToolbar;
    private CircleImageView circleImageView;
    private HeadImage hi;
    private ResponseLogin rl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);
        String user_name= App.getInstance().getUser(this).toString();
        QiutBtn = (Button) findViewById(R.id.qiutBtn);
////加载头像
//        /*获得当前登录用户的用户名*/
        circleImageView = findViewById(R.id.head);
        String user_name1=App.getInstance().getUser(UserActivity.this);
        HashMap<String, String> params = new HashMap<>();
        params.put("user_name",user_name1);
        JSONObject jsonObject = new JSONObject(params);
        OkGo.post(Api.GET_HEAD)
                .upJson(jsonObject.toString())
                .execute(new StringCallback() {

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        hi = new HeadImage();
                        hi = JsonUtils.fromJson(s,HeadImage.class);
                        if (!hi.getUrl().equals(" ")){
                            Glide
                                    .with(UserActivity.this)
                                    .load(hi.getUrl())
                                    .placeholder(R.drawable.loading)
                                    .error(R.drawable.error)
                                    .dontAnimate()
                                    .into((ImageView) circleImageView);
                        }
                    }
                });

        user = (TextView) findViewById(R.id.mUser_name);
        user.setText(user_name);
        settingsToolbar=(Toolbar) findViewById(R.id.UserToolbar);
        settingsToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UserActivity.this.finish();
            }
        });
        QiutBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MaterialDialog.Builder(UserActivity.this)
                        .title("提示")
                        .content("确定退出当前登录？")
                        .positiveText("确定")
                        .negativeText("取消")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                // 确定退出,移除sp中的用户名密码
                                App.getInstance().removeUser(UserActivity.this);
                                startActivity(new Intent(UserActivity.this,LoginActivity.class));
                                UserActivity.this.finish();
                            }
                        })
                        .onNegative(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                dialog.dismiss();
                            }
                        })
                        .show();
            }
        });
        circleImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectImage();
            }
        });

    }
    private void selectImage(){
        Intent intent1 = new Intent(Intent.ACTION_PICK);
        intent1.setType("image/*");
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
        startActivityForResult(intent1, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 1) {
            // 从相册返回的数据
            if (data != null) {
                // 得到图片的全路径
                Uri uri = data.getData();
                /**
                 *
                 */
                Bitmap bitmap = openImage(uri);
                saveBitmapToSharedPreferences(bitmap);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    /**
     * 将本地图片转成Bitmap
     * @param uri 已有图片的路径
     * @return bitmap resource
     */
    public Bitmap openImage(Uri uri){
        Bitmap bitmap = null;
        try{
            bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri);
        }catch(IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }
    //保存图片到SharedPreferences
    //处理上传前的图片
    private void saveBitmapToSharedPreferences(Bitmap bitmap) {
        // Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        //第一步:将Bitmap压缩至字节数组输出流ByteArrayOutputStream
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
        //第二步:利用Base64将字节数组输出流中的数据转换成字符串String
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        String imageString = new String(Base64.encodeToString(byteArray, Base64.DEFAULT));
        //上传图片
        saveToInternet(imageString,"");
    }
    /**
     * 上传图片到服务器
     */
    private void saveToInternet(String imgStr, String imgName) {
        //上传单个图片
        /*获得当前登录用户的用户名*/
        String user_name = App.getInstance().getUser(UserActivity.this);
        /*显示提示正在登录对话框*/
        final MaterialDialog md = new MaterialDialog.Builder(this)
                .title("提示")
                .content("图片正在上传，请稍等...")
                .progress(true, 0)
                .show();
        //构造请求体
        HashMap<String, String> params = new HashMap<>();
        params.put("user", user_name);
        params.put("image", imgStr);

        JSONObject jsonObject = new JSONObject(params);
        OkGo.<String>post(Api.UPLOAD_HEAD)
                .tag(this)//通过这个tag可以取消这个操作
                .upJson(jsonObject.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        //关闭提示框
                        md.dismiss();
                        rl = new ResponseLogin();
                        rl = JsonUtils.fromJson(s,ResponseLogin.class);
                        Toast.makeText(UserActivity.this, rl.getStatus(), Toast.LENGTH_SHORT).show();
                        //Toast.makeText(UploadImageActivity.this, ms.getMsg(), Toast.LENGTH_SHORT).show();
                        //Log.v("zj",ms.getMsg());
                    }
                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        md.dismiss();
                        Toast.makeText(UserActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                        super.onError(call, response, e);
                    }
                });
    }
}